package com.taptech.doufu.umeng.push;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import androidx.core.app.NotificationManagerCompat;
import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.BrowseActivity;
import com.taptech.doufu.ui.activity.EasyBrowseActivity;
import com.taptech.doufu.ui.activity.MainHomeActivity;
import com.taptech.doufu.ui.activity.NovelDetailsActivity;
import com.taptech.doufu.ui.activity.NovelSectionDetailsActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.event.EventBusCollectUnRead;
import com.taptech.doufu.event.EventBusHomePageSwitch;
import com.taptech.doufu.services.CartoonServices;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.fragment.weex.NotifyFragment;
import com.taptech.doufu.util.PackageUtils;
import com.taptech.doufu.util.StartActivityUtils;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.util.ui.NotificationUtils;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.entity.UMessage;
import com.umeng.message.inapp.IUmengInAppMsgCloseCallback;
import com.umeng.message.inapp.InAppMessageManager;
import com.umeng.message.tag.TagManager;
import org.android.agoo.common.AgooConstants;
import org.android.agoo.oppo.OppoRegister;
import org.android.agoo.vivo.VivoRegister;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class PushManager {
    private static final String TAG = "PushManager";

    private Context mContext;
    private PushAgent mPushAgent;

    private PushManager() {
        this.mContext = WeMediaApplication.applicationContext;
    }

    public static PushManager getInstance() {
        return Inner.instance;
    }

    private static class Inner{
        private static PushManager instance = new PushManager();
    }


    public void init() throws Exception{
        // 在此处调用基础组件包提供的初始化函数 相应信息可在应用管理 -> 应用信息 中找到 http://message.umeng.com/list/apps
        // 参数一：当前上下文context；
        // 参数二：应用申请的Appkey（需替换）；
        // 参数三：渠道名称；
        // 参数四：设备类型，必须参数，传参数为UMConfigure.DEVICE_TYPE_PHONE则表示手机；传参数为UMConfigure.DEVICE_TYPE_BOX则表示盒子；默认为手机；
        // 参数五：Push推送业务的secret 填充Umeng Message Secret对应信息（需替换）
        UMConfigure.preInit(mContext,Constant.U_PUSH_APP_KEY, "");
        UMConfigure.init(mContext, Constant.U_PUSH_APP_KEY, "", UMConfigure.DEVICE_TYPE_PHONE, Constant.U_PUSH_SECRET);
        //获取消息推送代理示例
        mPushAgent =  PushAgent.getInstance(mContext);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                TTLog.s("注册成功：deviceToken：-------->  " + deviceToken);
                addAlias();
                addTag(PackageUtils.getVersionName(mContext));
            }

            @Override
            public void onFailure(String s, String s1) {
                TTLog.s("注册失败：deviceToken：s-------->  " + s+" -----s1--->"+s1);

            }
        });


        //在线推送点击事件
        mPushAgent.setNotificationClickHandler(new UmengNotificationClickHandler(){

            @Override
            public void launchApp(Context context, UMessage uMessage) {
                super.launchApp(context, uMessage);
                //打开APP，主要在此处理逻辑
                handlerMsg(uMessage);
            }

        });

        mPushAgent.setMessageHandler(new UmengMessageHandler(){
            @Override
            public void dealWithCustomMessage(Context context, UMessage uMessage) {
                super.dealWithCustomMessage(context, uMessage);
                //处理自定义消息
                handlerMsg(uMessage);
            }
        });

        //消息透传
        mPushAgent.setPushIntentServiceClass(AppUmengNotificationService.class);

        //OPPO通道，参数1为app key，参数2为app secret
        OppoRegister.register(mContext, Constant.U_PUSH_OPPO_APP_KEY, Constant.U_PUSH_OPPO_APP_SECRET);
        //vivo 通道
        VivoRegister.register(mContext);

        InAppMessageManager.getInstance(mContext).setInAppMsgDebugMode(true);
    }

    /**
     * 添加别名
     * 别名增加，将某一类型的别名ID绑定至某设备，老的绑定设备信息还在，别名ID和device_token是一对多的映射关系
     */
    public void addAlias() {
        if (mPushAgent == null) {
            return;
        }
        if (TextUtils.isEmpty(AccountService.getInstance().getUserUid())) {
            return;
        }
        mPushAgent.addAlias(AccountService.getInstance().getUserUid(), Constant.ALIAS_TYPE, new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String message) {
            }
        });
    }



    /**
     * 移除别名
     */
    public void deleteAlias() {
        if (mPushAgent == null) {
            return;
        }
        if (TextUtils.isEmpty(AccountService.getInstance().getUserUid())) {
            return;
        }
        mPushAgent.deleteAlias(AccountService.getInstance().getUserUid(), Constant.ALIAS_TYPE, new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String message) {
            }
        });
    }

    public void addTag(String tag) {
        if (mPushAgent == null) {
            return;
        }
        if (TextUtils.isEmpty(tag)) {
            return;
        }
        mPushAgent.getTagManager().addTags(new TagManager.TCallBack() {
            @Override
            public void onMessage(boolean b, ITagManager.Result result) {

            }
        },tag);
    }

    /**
     * Push后台进行日活统计及多维度推送
     * @param context
     */
    public void onAppStart(Context context) {
        PushAgent.getInstance(context).onAppStart();
    }

    public void handlerMsg(Intent intent) {
        if (intent == null) {
            return;
        }
        String body = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
        if (!TextUtils.isEmpty(body)) {
            JSONObject bodyJson = JSON.parseObject(body);
            JSONObject extra = bodyJson.getJSONObject("extra");
            Iterator iterator = extra.entrySet().iterator();
            Map<String, String> params = new HashMap<>();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                params.put(entry.getKey().toString(), entry.getValue().toString());
            }
            handlerMsg(params);
        }
    }

    private void handlerMsg(UMessage uMessage) {
        if (uMessage != null) {
            handlerMsg(uMessage.extra);
        }
    }

    private void handlerMsg(Map<String,String> params) {
        if (params != null) {
            String msgType = params.get(ParamsName.MSG_TYPE);
            String pageUrl = params.get(ParamsName.PAGE_URL);
            String dataUrl = params.get(ParamsName.DATA_URL);
            String title = params.get(ParamsName.TITLE);
            String id = params.get(ParamsName.ID);
            String index = params.get(ParamsName.INDEX);
            String unReadCount = params.get(ParamsName.UN_READ_COUNT);
            String novelDetail = params.get(ParamsName.NOVEL_DETAIL);
            if (TextUtils.isEmpty(msgType)) {
                return;
            }
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            switch (Integer.parseInt(msgType)) {
                case MsgType.MSG_TYPE_NOVEL_DETAIL:
                    NovelDetailsActivity.Companion.startActivity(mContext,id,Intent.FLAG_ACTIVITY_NEW_TASK);
                    break;
                case MsgType.MSG_TYPE_WEEX:
                    if ("1".equals(novelDetail) && !TextUtils.isEmpty(id)) {
                        NovelDetailsActivity.Companion.startActivity(mContext,id,Intent.FLAG_ACTIVITY_NEW_TASK);
                    }else{
                        SimpleWeexActivity.startActivity(mContext,pageUrl, (HashMap) params,Intent.FLAG_ACTIVITY_NEW_TASK);
                    }
                    break;
                case MsgType.MSG_TYPE_INSIDE_WEB:
                    intent.setClass(mContext, BrowseActivity.class);
                    intent.putExtra(com.taptech.doufu.constant.Constant.URL, pageUrl);
                    intent.putExtra(com.taptech.doufu.constant.Constant.TITLE, title);
                    mContext.startActivity(intent);
                    break;
                case MsgType.MSG_TYPE_OUTSIDE_WEB:
                    intent.setClass(mContext, EasyBrowseActivity.class);
                    intent.putExtra(com.taptech.doufu.constant.Constant.URL, pageUrl);
                    intent.putExtra(com.taptech.doufu.constant.Constant.TITLE, title);
                    mContext.startActivity(intent);
                    break;
                case MsgType.MSG_TYPE_ALBUM_HORIZONTAL_COVER:
                    intent.putExtra(com.taptech.doufu.constant.Constant.URL, dataUrl);
                    intent.putExtra(com.taptech.doufu.constant.Constant.TITLE, title);
                    intent.putExtra("IS_FROMHOME", true);
                    new StartActivityUtils(mContext, intent).toNovelMoreActivity();
                    break;
                case MsgType.MSG_TYPE_ALBUM_VERTICAL_COVER:
                    intent.putExtra(com.taptech.doufu.constant.Constant.URL, dataUrl);
                    intent.putExtra(com.taptech.doufu.constant.Constant.TITLE, title);
                    intent.putExtra("IS_FROMHOME", true);
                    new StartActivityUtils(mContext, intent).toNovelMoreActivity();
                    break;
                case MsgType.MSG_TYPE_READER_NOVEL:
                    intent.setClass(mContext, NovelSectionDetailsActivity.class);
                    intent.putExtra(com.taptech.doufu.constant.Constant.ARTICLE_NOVELID, id);
                    mContext.startActivity(intent);
                    break;
                case MsgType.MSG_TYPE_READER_COMIC:
                    CartoonServices.enterCartoonScanNewActivity(mContext, id, -1, true,Intent.FLAG_ACTIVITY_NEW_TASK);
                    break;
                case MsgType.MSG_TYPE_MAIN_BOTTOM_TAB:
                    intent.setClass(mContext, MainHomeActivity.class);
                    intent.putExtra("index", Integer.parseInt(index));
                    mContext.startActivity(intent);
                    break;
                case MsgType.MSG_TYPE_HOME_TOB_TAB:
                    //先跳转到首页
                    intent.setClass(mContext, MainHomeActivity.class);
                    intent.putExtra("index", 0);
                    mContext.startActivity(intent);
                    //发送Event通知首页卡片切换频道
                    EventBusHomePageSwitch event = new EventBusHomePageSwitch();
                    event.setIndex(Integer.parseInt(index));
                    event.setTag(EventBusHomePageSwitch.tag);
                    EventBus.getDefault().post(event);
                    break;
                case MsgType.MSG_TYPE_BOOK_SHELF_UN_READ:
                    //书架小红点、不用弹出通知栏
                    if (Integer.parseInt(unReadCount) > 0) {
                        //显示小红点
                        EventBusCollectUnRead eventBusCollectUnRead = new EventBusCollectUnRead();
                        eventBusCollectUnRead.setTag(EventBusCollectUnRead.TAG_BOOK_SHELF);
                        eventBusCollectUnRead.setShow(true);
                        EventBus.getDefault().post(eventBusCollectUnRead);
                    }else{
                        //隐藏小红点
                        EventBusCollectUnRead.clearUnRead();
                    }
                    break;
                case MsgType.MSG_TYPE_MY_MSG_UN_READ:
                    NotifyFragment.refrush();
                    break;
            }
        }
    }



    private static final String channelId = "doufu";
    private static final String channelName = "推送通知";

    public void addNotification(Intent intent){
        String msg = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        JSONObject msgJson = JSON.parseObject(msg);
        if (msgJson == null) {
            return;
        }

        JSONObject extra = msgJson.getJSONObject("extra");
        if (extra == null) {
            return;
        }
        int msgType = extra.getInteger(ParamsName.MSG_TYPE);
        if (msgType == MsgType.MSG_TYPE_BOOK_SHELF_UN_READ) {
            int unReadCount = extra.getInteger(ParamsName.UN_READ_COUNT);
            //书架小红点、不用弹出通知栏
            if (unReadCount > 0) {
                //显示小红点
                EventBusCollectUnRead eventBusCollectUnRead = new EventBusCollectUnRead();
                eventBusCollectUnRead.setTag(EventBusCollectUnRead.TAG_BOOK_SHELF);
                eventBusCollectUnRead.setShow(true);
                EventBus.getDefault().post(eventBusCollectUnRead);
            }else{
                //隐藏小红点
                EventBusCollectUnRead.clearUnRead();
            }

        } else if (msgType == MsgType.MSG_TYPE_MY_MSG_UN_READ) {
            //消息小红点、不用弹出通知栏
            NotifyFragment.refrush();
        } else {

            JSONObject bodyJson = msgJson.getJSONObject("body");
            if (bodyJson == null) {
                return;
            }
            String title = bodyJson.getString("title");
            String subTitle = bodyJson.getString("text");
            if (TextUtils.isEmpty(title) && TextUtils.isEmpty(subTitle)) {
                return;
            }
            //在通知栏中显示
            int id = (int) (System.currentTimeMillis() / 1000);
            NotificationUtils.INSTANCE.createNotificationChannel(mContext,channelId,channelName,NotificationManager.IMPORTANCE_DEFAULT);
            intent.setClass(mContext, UmengNotificationClickReceiver.class);
            PendingIntent pendingIntent = PendingIntent.
                    getBroadcast(mContext, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            Notification.Builder builder = new Notification.Builder(mContext)
                    .setContentTitle(title)
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis())
                    .setAutoCancel(true)
                    .setSmallIcon(R.drawable.new_icon)
                    .setContentText(subTitle);
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
                builder.setChannelId(channelId);
            }
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(mContext);
            notificationManagerCompat.notify(id, builder.build());

            if (!NotificationUtils.INSTANCE.areNotificationsEnabled(mContext,channelId)) {
                try {
                    //未开通权限进行忽略统计
                    org.json.JSONObject jsonObject = new org.json.JSONObject(msg);
                    UMessage uMessage = new UMessage(jsonObject);
                    UTrack.getInstance(mContext).trackMsgDismissed(uMessage);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
    }






    /**
     * 应用内推送弹窗
     * @param activity
     * @param key
     */
    public void inAppMessage(Activity activity,String key) {
        if (!TextUtils.isEmpty(key)) {
            InAppMessageManager.getInstance(activity).showCardMessage(activity, key, new IUmengInAppMsgCloseCallback() {
                @Override
                public void onClose() {

                }
            });
        }
    }


}
